package com.ruoyi.sysem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.sysem.domain.BorrowUser;
import com.ruoyi.sysem.domain.from.LoginUser;
import com.ruoyi.sysem.mapper.UserMapper;
import com.ruoyi.sysem.service.UserService;
import com.ruoyi.sysem.util.ResultObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {



    @Autowired
    UserMapper userMapper;



    @Override
    public ResultObject<Map> login(LoginUser loginUser) {
        String loginName = loginUser.getUname();
        String rawpassword = loginUser.getPassword();
        QueryWrapper<BorrowUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BorrowUser::getUname,loginName);
        List<BorrowUser> users = userMapper.selectList(queryWrapper);
        if(users.size()==0){
            return new ResultObject<>(false,"0","用户名密码错误",null);
        }
        BorrowUser borrowUser = users.get(0);
        Integer id = borrowUser.getUid();
        String password = borrowUser.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(!bCryptPasswordEncoder.matches(rawpassword,password)){
            return new ResultObject<>(false,"0","用户名密码错误",null);
        }

        //String token = JwtUtils.createToken(id.toString(), borrowUser.getUname(), null);
        Map map= new HashMap<>();
        map.put("loginName",loginName);
        map.put("password",password);
        map.put("userId",id);
        return new ResultObject<>(true,"1","登录成功",map);

    }

    @Override
    public List<BorrowUser> selectUserList(BorrowUser borrowUser) {
        QueryWrapper<BorrowUser> queryWrapper = new QueryWrapper<>();
        List<BorrowUser> borrowUsers = userMapper.selectList(queryWrapper);
        return borrowUsers;
    }

    @Override
    public int updateUser(BorrowUser borrowUser) {
        int i = userMapper.updateById(borrowUser);
        return i;
    }

}
